package cn.lx.auth.secutity.filter;

import cn.hsa.hsaf.core.framework.web.WrapperResponse;
import cn.lx.auth.secutity.entity.PortalUserDetails;
import cn.lx.auth.secutity.utils.ApiVerifyUtil;
import cn.lx.auth.secutity.utils.AuthPropertiesUtil;
import cn.lx.auth.secutity.utils.SessionToUserUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName UserContextFilter
 * @Description: //todo
 * @Author: 落雪
 * @CreateDate: 2025/7/14 23:22
 * @UpdateUser: 落雪
 * @UpdateDate: 2025/7/14 23:22
 * @UpdateRemark:
 * @Version: 1.0
 */
public class UserContextFilter implements Filter {
    public UserContextFilter() {
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httprequest = (HttpServletRequest)request;
        HttpServletResponse httpresponse = (HttpServletResponse)response;
        boolean permitsFlag = false;
        String permits = "/api/**,/*/api/**," + AuthPropertiesUtil.permits;
        String requestUrl = httprequest.getServletPath().toString();
        PathMatcher matcher = new AntPathMatcher();
        if (!StringUtils.isEmpty(permits)) {
            for(int i = 0; i < permits.split(",").length; ++i) {
                String exclusions = permits.split(",")[i];
                if (!"".equals(exclusions) && matcher.match(exclusions, requestUrl)) {
                    permitsFlag = true;
                    break;
                }
            }
        }

        if (permitsFlag) {
            filterChain.doFilter(request, response);
        } else {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            SessionToUserUtil sessToUser;
            PortalUserDetails userDetalis;
            if (authentication != null) {
                userDetalis = (PortalUserDetails)authentication.getPrincipal();
                if (httprequest.getSession().getAttribute("CurrentUser") == null) {
                    httprequest.getSession().setAttribute("CurrentUser", userDetalis);
                }

                sessToUser = new SessionToUserUtil();
                sessToUser.toCurrentUser(userDetalis);
                filterChain.doFilter(request, response);
            } else if (httprequest.getSession().getAttribute("CurrentUser") != null) {
                userDetalis = (PortalUserDetails)httprequest.getSession().getAttribute("CurrentUser");
                sessToUser = new SessionToUserUtil();
                sessToUser.toCurrentUser(userDetalis);
                filterChain.doFilter(request, response);
            } else {
                ApiVerifyUtil apiVerifyUtil = new ApiVerifyUtil();
                if (apiVerifyUtil.whiteListVerify(httprequest.getServletPath().toString())) {
                    filterChain.doFilter(request, response);
                } else {
                    httpresponse.setCharacterEncoding("UTF-8");
                    httpresponse.setContentType("application/json; charset=utf-8");
                    PrintWriter out = httpresponse.getWriter();
                    JSONObject res = new JSONObject();
                    res.put("code", -4);
                    res.put("type", WrapperResponse.ResponseType.TYPE_ERROR);
                    res.put("message", "调用非白名单，无法获取用户信息");
                    res.put("data", "");
                    out.append(res.toString());
                    out.flush();
                    out.close();
                }
            }
        }

    }

    public void destroy() {
    }
}

